package dproxy.application;

import java.io.File;
import java.text.DecimalFormat;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import dproxy.application.ui.CommandLineProcessor;
import dproxy.server.ServerLoader;
import dproxy.server.common.DPConstants;

/**
 * Class that starts the application. It starts a ServerLoader, which 
 * will load a set of servers.
 * TODO [4] When error loading application (ex. two in stances - tcp port conflict), show error and ask for "enter" key, then exit 
 * TODO [4] Shutdown hook to catch ctrl-c / window close
 */
public final class Main {

    /** Root where JAR and xml files will be deployed. */
    private static final String DEPLOYMENT_ROOT = "../deploy/";
    
    /** Logger instance. */
    private Log logger = LogFactory.getLog(getClass());
    
    /**
     * Private constructor.
     */
    private Main() {
    }
    
    /**
     * DProxy begin.
     * @param args Command-line arguments
     */
    public static void main(String[] args) {
        Main main = new Main();
        main.begin(args);
    }

    /**
     * DProxy begin.
     * @param args Command line arguments
     */
    private void begin(String[] args) {
        long startTime = System.currentTimeMillis();
        logger.info("Starting server");
        File deploymentRoot = new File(DEPLOYMENT_ROOT);
        
        // Starts the Server Manager infrastructure
        ServerLoader manager = new ServerLoader(deploymentRoot);
        manager.start();
        long endTime = System.currentTimeMillis();
        float startUpTime 
                = (float) (endTime - startTime) 
                    / DPConstants.THOUSAND;
        logger.info(
                "Servers started in " + 
                DecimalFormat.getInstance().format(startUpTime) +
                " seconds");
        
        // Starts processing command-line parameters
        CommandLineProcessor.getInstance().run();
        
        // When CLP ends, the application is finished
        logger.info("Stopping server...");
        manager.stop();
    }

}
